package cs575.update.services;

import java.io.IOException;
import java.net.Socket;
import java.nio.ByteBuffer;

import cs575.common.FantasyMessage;
import cs575.common.OpCodes;
import cs575.common.Player.Position;

public class AddPlayer {

	public void execute(String ip, int port, String name, Position position) {
		int messageSize = 4 + name.getBytes().length + 4;
		ByteBuffer bb = ByteBuffer.allocate(messageSize);

		bb.putInt(name.getBytes().length);
		bb.put(name.getBytes());
		bb.putInt(position.ordinal());

		FantasyMessage message = new FantasyMessage();
		message.setOpCode(OpCodes.ADD_PLAYER);
		message.setMessage(bb.array());

		try {
			Socket socket = new Socket(ip, port);
			socket.getOutputStream().write(message.toBytes());
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
